/*
 * @Description: 新增元数据继承配置弹窗组件
 * @Author: Rfan
 * @Date: 2022-05-30 14:43:58
 * @LastEditTime: 2022-06-16 16:38:57
 */

import { Button, Form, Modal } from 'antd';
import { FC, useState } from 'react';
import InheritForm from './common/InheritForm';
import { useMetadataInheritContext } from '../../contexts/MetadataInheritContext';
import type { ICommonDialog } from '@/interfaces/global';
import { selectItemByKey } from '@/utils/list';
import { jsonClone } from '@/utils';

interface AddDialogProps extends ICommonDialog {}

const AddDialog: FC<AddDialogProps> = (props) => {
  const { visible, onClose } = props;
  const { selectAT, selectLevel, levelMatedata, addInheritFunc } = useMetadataInheritContext();
  const [form] = Form.useForm();

  const [meatdataLevels, setMeatdataLevels] = useState({ current: 0, upper: 0 });

  const getFieldsLevel = (current: number, upper: number): void => {
    if (current !== undefined && upper !== undefined) {
      setMeatdataLevels({ current, upper });
    }
  };

  // 提交表单
  const submitFunc = () => {
    form.submit();
  };

  // 新增档案类型
  const onFinish = (val: any) => {
    const values = jsonClone(val);
    const ruleMetadata: any = selectItemByKey(
      values.ruleDataId,
      levelMatedata[meatdataLevels.upper]
    );
    const targetMetadata: any = selectItemByKey(
      values.targetDataId,
      levelMatedata[meatdataLevels.current]
    );
    values.archiveTypeId = selectAT.id;
    values.atCode = selectAT.atCode;
    values.atType = selectAT.atType;
    values.level = selectLevel.level;
    values.isLinkage = values.isLinkage ? 0 : 1;
    values.inheritRuleData = {
      field_desc: ruleMetadata.field_desc,
      field_name: ruleMetadata.field_name,
      level: meatdataLevels.upper
    };

    values.targetData = {
      field_desc: targetMetadata.field_desc,
      field_name: targetMetadata.field_name,
      level: meatdataLevels.current
    };
    delete values.ruleDataId;
    delete values.targetDataId;
    console.log('add finish ', values);
    addInheritFunc(values).then(() => {
      onCancel();
    });
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };
  const onCancel = () => {
    onClose();
  };

  return (
    <Modal
      destroyOnClose
      title="新建"
      visible={visible}
      width={600}
      onCancel={onCancel}
      footer={[
        <Button key="back" onClick={onCancel}>
          取消
        </Button>,
        <Button key="submit" type="primary" onClick={submitFunc}>
          保存
        </Button>
      ]}
    >
      <Form
        form={form}
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 14 }}
        preserve={false}
        initialValues={{ isLinkage: true, relationType: 0, isValid: 0 }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
      >
        <InheritForm getFieldsLevel={getFieldsLevel} />
      </Form>
    </Modal>
  );
};

export default AddDialog;
